import { defineStore } from 'pinia';

/**
 * 验证码相关的Store
 * 用于管理图形验证码的生成和验证
 */
export const useCaptchaStore = defineStore('captcha', {
  state: () => ({
    // 图形验证码相关
    imageCaptcha: {
      code: '', // 验证码内容（仅在开发环境中存储，生产环境应该只在服务端验证）
      image: '', // 验证码图片的base64字符串
      timestamp: 0, // 验证码生成时间戳
    },
    // 短信验证码相关
    smsCaptcha: {
      phone: '', // 发送验证码的手机号
      timestamp: 0, // 发送时间戳
      countdown: 0, // 倒计时（秒）
    }
  }),
  
  getters: {
    // 获取图形验证码图片
    getImageCaptcha: (state) => state.imageCaptcha.image,
    
    // 获取短信验证码倒计时
    getSmsCountdown: (state) => state.smsCaptcha.countdown,
    
    // 判断是否可以发送短信验证码
    canSendSms: (state) => state.smsCaptcha.countdown === 0
  },
  
  actions: {
    /**
     * 生成随机验证码
     * @param {number} length 验证码长度
     * @returns {string} 生成的验证码
     */
    generateRandomCode(length = 4) {
      const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      let result = '';
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      return result;
    },
    
    /**
     * 生成图形验证码
     * @returns {string} 验证码图片的base64字符串
     */
    generateImageCaptcha() {
      // 生成随机验证码
      const code = this.generateRandomCode(4);
      this.imageCaptcha.code = code;
      this.imageCaptcha.timestamp = Date.now();
      
      // 创建canvas元素
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = 100;
      canvas.height = 36;
      
      // 绘制背景
      ctx.fillStyle = '#f0f0f0';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      // 绘制干扰线
      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = this.getRandomColor(40, 180);
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
      }
      
      // 绘制干扰点
      for (let i = 0; i < 50; i++) {
        ctx.fillStyle = this.getRandomColor(0, 255);
        ctx.beginPath();
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
        ctx.fill();
      }
      
      // 绘制验证码
      ctx.font = 'bold 24px Arial';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      for (let i = 0; i < code.length; i++) {
        ctx.fillStyle = this.getRandomColor(10, 100);
        ctx.fillText(
          code.charAt(i),
          20 + i * 20,
          canvas.height / 2 + Math.random() * 8 - 4
        );
      }
      
      // 转换为base64图片
      const base64 = canvas.toDataURL('image/png');
      this.imageCaptcha.image = base64;
      
      return base64;
    },
    
    /**
     * 获取随机颜色
     * @param {number} min 最小值
     * @param {number} max 最大值
     * @returns {string} 颜色值
     */
    getRandomColor(min, max) {
      const r = min + Math.floor(Math.random() * (max - min));
      const g = min + Math.floor(Math.random() * (max - min));
      const b = min + Math.floor(Math.random() * (max - min));
      return `rgb(${r},${g},${b})`;
    },
    
    /**
     * 验证图形验证码
     * @param {string} code 用户输入的验证码
     * @returns {boolean} 验证结果
     */
    verifyImageCaptcha(code) {
      if (!code || !this.imageCaptcha.code) return false;
      
      // 验证码有效期为5分钟
      const now = Date.now();
      const validPeriod = 5 * 60 * 1000; // 5分钟
      
      if (now - this.imageCaptcha.timestamp > validPeriod) {
        return false;
      }
      
      // 不区分大小写比较
      return code.toUpperCase() === this.imageCaptcha.code.toUpperCase();
    },
    
    /**
     * 开始短信验证码倒计时
     * @param {string} phone 手机号
     */
    startSmsCountdown(phone) {
      this.smsCaptcha.phone = phone;
      this.smsCaptcha.timestamp = Date.now();
      this.smsCaptcha.countdown = 60;
      
      // 启动倒计时
      const timer = setInterval(() => {
        if (this.smsCaptcha.countdown > 0) {
          this.smsCaptcha.countdown--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },
    
    /**
     * 重置短信验证码状态
     */
    resetSmsCountdown() {
      this.smsCaptcha.countdown = 0;
    }
  }
});